package org.lisy.java.io;

import java.io.File;
import java.io.IOException;

public class FileOperate {

	public static void main(String[] args) {

		File dir = new File("./deploy/target/file");
		File file = new File("./deploy/target/file/name.txt");
		File renameFile = new File("./deploy/target/file/rename.txt");

		// 删除目录及文件
		deleteFile(dir);

		// 创建文件
		createFile(file);

		// 重命名
		renameFile(file, renameFile);
	}

	private static boolean deleteFile(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteFile(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		boolean delete = dir.delete();
		System.out.println("delete file: " + dir.getName());
		return delete;
	}

	private static boolean createFile(File file) {
		try {
			if (!file.exists()) {
				// 如果上级不存在，就会自动创建
				boolean mkdirs = file.getParentFile().mkdirs();
				System.out.println("create mkdirs: " + mkdirs);
				boolean createNewFile = file.createNewFile();
				System.out.println("create file: " + createNewFile);
			}
			return true;
		} catch (IOException e) {
			System.out.println("file operate fail : " + e.toString());
		}
		return false;
	}

	private static boolean renameFile(File file, File renameFile) {
		boolean renameTo = file.renameTo(renameFile);
		System.out.println("rename file: " + renameTo);
		return renameTo;
	}
}
